<template>
  <el-select
    v-model="selectedValue"
    filterable
    remote
    reserve-keyword
    placeholder="请输入小区名称搜索"
    :remote-method="remoteMethod"
    :loading="loading"
    :clearable="true"
    @change="handleChange"
    @clear="handleClear"
    style="width: 100%"
  >
    <el-option
      v-for="item in options"
      :key="item.sectId"
      :label="item.stNameFrst"
      :value="item.sectId"
    >
      <span style="float: left">{{ item.stNameFrst }}</span>
      <span style="float: right; color: #8492a6; font-size: 13px">
        {{ item.hpbName }} - {{ item.strName }}
      </span>
    </el-option>
  </el-select>
</template>

<script>
import { getBaseInformation } from "@/api/manage/approval";

export default {
  name: "ChooseArea",
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      selectedValue: this.value,
      options: [],
      loading: false,
      queryParams: {
        pageNumber: 1,
        pageSize: 50,
        stNameFrst: "",
      },
    };
  },
  watch: {
    value(newVal) {
      this.selectedValue = newVal;
    },
    selectedValue(newVal) {
      this.$emit("input", newVal);
    },
  },
  methods: {
    // 远程搜索方法
    async remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        this.queryParams.stNameFrst = query;
        try {
          const response = await getBaseInformation(this.queryParams);
          console.log(response, "response");

          if (response.errorCode === "000000") {
            this.options = response.data || [];
          } else {
            this.$message.error(response.msg || "搜索失败");
            this.options = [];
          }
        } catch (error) {
          console.error("搜索失败:", error);
          this.$message.error("搜索失败");
          this.options = [];
        } finally {
          this.loading = false;
        }
      } else {
        this.options = [];
      }
    },

    // 选择变化
    handleChange(value) {
      const selectedOption = this.options.find((item) => item.sectId === value);
      this.$emit("change", selectedOption);
    },

    // 清空选择
    handleClear() {
      this.$emit("change", null);
    },
  },
};
</script>

<style lang="scss" scoped>
// 可以添加自定义样式，如果需要的话
</style>
